package jsyf.oa.web.contract;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import jsyf.com.constant.SendConstant;
import jsyf.com.util.BaseUtils;
import jsyf.com.util.ExportCustomerExcel;
import jsyf.com.util.ExportExcel;
import jsyf.com.util.FastJsonConvert;
import jsyf.com.util.ResponseUtils;
import jsyf.oa.facade.contract.ContractMainFacade;
import jsyf.oa.facade.wechat.service_company.TokenFacade;
import jsyf.oa.web.sender.Sender;
import jsyf.oa.web.socket.MyWebSocketHandler;
import jsyf.oa.web.until.WordDocExport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.socket.TextMessage;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


@Api(value = "合同查询接口", description = "合同查询接口")
@Controller
@RequestMapping("/contractMain")
public class ContractMainController {

    @Resource
    private ContractMainFacade contractMainFacade;
    @Resource
    private TokenFacade tokenFacade;
    @Autowired
    private MyWebSocketHandler myWebSocketHandler;

    @RequestMapping(value = "/selectMainList.json", method = RequestMethod.POST)
    public void select(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = this.contractMainFacade.selectMainList(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(result));
    }

    @RequestMapping(value = "/selectContractList.json", method = RequestMethod.POST)
    public void selectContractList(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = this.contractMainFacade.selectContractList(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(result));
    }

    @RequestMapping(value = "/save.json", method = RequestMethod.POST)
    public void save(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = contractMainFacade.save(jsonData);
        boolean flag = Boolean.parseBoolean(result.getString("flag"));
        //发送消息
        sendMessage(result.getString("message"));
        if (flag) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond("保存成功"));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("保存失败"));
        }
    }

    @RequestMapping(value = "/receivableSave.json", method = RequestMethod.POST)
    public void receivableSave(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = contractMainFacade.receivableSave(jsonData);
        boolean flag = Boolean.parseBoolean(result.getString("flag"));
        if (flag) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond("保存成功"));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("保存失败"));
        }
    }

    @RequestMapping(value = "/selectContractById.json", method = RequestMethod.POST)
    public void selectContract(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = this.contractMainFacade.selectContractById(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjHourRespond(result));
    }

    @RequestMapping(value = "/getAcountRepaymentListById.json", method = RequestMethod.POST)
    public void getAcountRepaymentListById(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = this.contractMainFacade.getAcountRepaymentListById(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjHourRespond(result));
    }

    @RequestMapping(value = "/saveAcountRepaymentListById.json", method = RequestMethod.POST)
    public void saveAcountRepaymentListById(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = this.contractMainFacade.saveAcountRepaymentListById(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjHourRespond(result));
    }

    @RequestMapping(value = "/selectContractAccountById.json", method = RequestMethod.POST)
    public void selectContractAccountById(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = this.contractMainFacade.selectContractAccountById(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjHourRespond(result));
    }

    @RequestMapping(value = "/updateContractAccountMoney.json", method = RequestMethod.POST)
    public void updateContractAccountMoney(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = this.contractMainFacade.updateContractAccountMoney(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjHourRespond(result));
    }

    @RequestMapping(value = "/newContract.json", method = RequestMethod.POST)
    public void newContract(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject records = this.contractMainFacade.newContract(jsonData);
        if (records != null) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjHourRespond(records));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("未找到数据"));
        }
    }

    @RequestMapping(value = "/applyAudit.json", method = RequestMethod.POST)
    public void applyAudit(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = contractMainFacade.applyAudit(jsonData);
        boolean flag = Boolean.parseBoolean(result.getString("flag"));
        //发送消息
        sendMessage(result.getString("message"));
        if (flag) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond("审核成功"));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("审核驳回"));
        }
    }

    @RequestMapping(value = "/downResumeDoc.json", method = RequestMethod.GET)
    public String downResumeDoc(HttpServletResponse response, HttpServletRequest request, @RequestParam String contractId)
            throws IOException {
        request.setCharacterEncoding("utf-8");
        JSONObject result = this.contractMainFacade.downDocById(contractId);
        JSONObject results = JSONObject.parseObject(BaseUtils.succsessDocRespond(result));
        JSONObject main = results
                .getJSONObject("contract")
                .getJSONObject("main");
        String buyType = main.getString("buyType");
        String province = main.getString("province");
        String createTime = main.getString("createTime");
        String regionManagerName = main.getString("regionManagerName");
        String buyer = main.getString("buyer");
        String modelName = main.getString("modelName");
        String contractType = main.getString("contractType");
        String payment = "";
        String filename = "";
        if ("1".equalsIgnoreCase(contractType)) {
            if ("全款".equals(buyType)) {
                payment = "fullPayment";
            } else if ("内部分期".equals(buyType)) {
                payment = "installPayment";
            } else if ("融资租赁".equals(buyType)) {
                payment = "financingPayment";
            } else {
                payment = "financBaoPayment";
            }
            filename = createTime
                    + "-"
                    + province
                    + "-"
                    + buyType
                    + "-"
                    + regionManagerName
                    + "-"
                    + buyer
                    + "-"
                    + modelName
                    + ".doc";
        } else {
            payment = "oldPayment";
            filename = createTime
                    + "-"
                    + province
                    + "-"
                    + buyType
                    + "-"
                    + regionManagerName
                    + "-"
                    + buyer
                    + "-"
                    + modelName
                    + ".doc";
        }

        //否则Freemarker的模板在处理时可能会因为找不到值而报错，这里暂时忽略这个步骤
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            //调用工具类WordGenerator的createDoc方法生成Word文档
            WordDocExport.fileDoc(buyType, contractType);
            file = WordDocExport.createDoc(results, payment);
            fin = new FileInputStream(file);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String((filename).getBytes("GB2312"), "iso8859-1"));
            out = response.getOutputStream();
            byte[] buffer = new byte[1024];//缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (fin != null) fin.close();
            if (out != null) out.close();
            if (file != null) file.delete(); // 删除临时文件
        }
        return null;
    }

    @RequestMapping(value = "/getUploadFileByContractId.json", method = RequestMethod.POST)
    public void getUploadFileByContractId(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = this.contractMainFacade.getUploadFileByContractId(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(result));
    }


    @RequestMapping(value = "/uploadFileByContractId.json", method = RequestMethod.POST)
    public void uploadFileByContractId(HttpServletResponse response, @RequestBody String jsonData) {
        if (contractMainFacade.uploadFileByContractId(jsonData)) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond("审核成功"));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("审核驳回"));
        }
    }

    @RequestMapping(value = "/getNameAndTel.json", method = RequestMethod.POST)
    public void getNameAndTel(HttpServletResponse response, @RequestBody String jsonData) {
        List<JSONObject> result = this.contractMainFacade.getNameAndTel(jsonData);
        if (null != result && result.size() > 0) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessArrRespond(result));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("未找到数据"));
        }
    }

    @RequestMapping(value = "/senderExpireList.json", method = RequestMethod.POST)
    public void senderExpireList(HttpServletResponse response, @RequestBody String jsonData) {
        List<JSONObject> result = this.contractMainFacade.senderExpireList(jsonData);
        if (null != result && result.size() > 0) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessArrRespond(result));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("未找到数据"));
        }
    }

    @RequestMapping(value = "/getRegionManagerByUserId.json", method = RequestMethod.POST)
    public void getRegionManagerByUserId(HttpServletResponse response, @RequestBody String jsonData) {
        List<JSONObject> result = this.contractMainFacade.getRegionManagerByUserId(jsonData);
        if (null != result && result.size() > 0) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessArrRespond(result));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("未找到数据"));
        }
    }

    @RequestMapping(value = "/remove.json", method = RequestMethod.POST)
    public void remove(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("records", contractMainFacade.remove(jsonData));
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(jsonObject));
    }

    @RequestMapping(value = "/obsolete.json", method = RequestMethod.POST)
    public void obsolete(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("records", contractMainFacade.obsolete(jsonData));
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(jsonObject));
    }

    @RequestMapping(value = "/selectContractAccountList.json", method = RequestMethod.POST)
    public void selectContractAccountList(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = this.contractMainFacade.selectContractAccountList(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(result));
    }

    /*
    导出应收台账
     */
    @RequestMapping(value = "/exportContractAccountList.json", method = RequestMethod.GET)
    public void exportContractAccountList(HttpServletResponse response, @RequestParam String checkedAccounts) throws Exception {
        //导出表名、列名
        String title = "应收台账";
        String[] rowsName = checkedAccounts.split(",");
        String[] cellName = checkedAccounts.split(",");
        for (int i = 0; i < rowsName.length; i++) {
            System.out.println(rowsName[i]);

            rowsName[i] = rowsName[i].substring(rowsName[i].lastIndexOf("-") + 1, rowsName[i].length());
        }
        System.out.println(rowsName);
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs = null;
        List<JSONObject> jsonObjectList = contractMainFacade.exportContractAccountList();
        for (int i = 0; i < jsonObjectList.size(); i++) {
            JSONObject jsonObject = jsonObjectList.get(i);
            objs = new Object[rowsName.length];

            if (StringUtils.isBlank(jsonObjectList.get(i).getString("customerCredit"))) {
                if (jsonObjectList.get(i).getString("haveOverdue").equals("1")) {
                    Integer overdueNo = Integer.parseInt(jsonObjectList.get(i).getString("haveOverdueNo"));
                    if (overdueNo <= 30) {
                        jsonObjectList.get(i).put("customerCredit", "B类：逾期1-30天");
                    } else if (31 < overdueNo && overdueNo <= 60) {
                        jsonObjectList.get(i).put("customerCredit", "B-A类：逾期31-60天");
                    } else {
                        jsonObjectList.get(i).put("customerCredit", "A类：逾期60天以上");
                    }
                } else {
                    jsonObjectList.get(i).put("customerCredit", "C类：无逾期");
                }
            }
            for (int j = 0; j < cellName.length; j++) {
                if (rowsName[j].equals("是否结清")) {
                    if (jsonObject.getString(cellName[j].substring(0, cellName[j].lastIndexOf("-"))).equals("1")) {
                        objs[j] = "是";
                    } else {
                        objs[j] = "否";
                    }
                } else {
                    objs[j] = jsonObject.getString(cellName[j].substring(0, cellName[j].lastIndexOf("-")));
                }
            }
            dataList.add(objs);
        }
        ExportExcel ex = new ExportExcel(title, rowsName, dataList, response);
        ex.export();
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond("导出成功"));
    }

    @RequestMapping(value = "/getDownByCondition.json", method = RequestMethod.GET)
    public void getDownByCondition(HttpServletResponse response, @RequestParam String userId, @RequestParam String customerKey, @RequestParam String auditFlag, @RequestParam String haveSettle, @RequestParam String selectCom, @RequestParam String haveDelivery, @RequestParam String fieldList) throws Exception {
        //查出来的数据
        List<JSONObject> jsonObjectList = null;
        jsonObjectList = this.contractMainFacade.getAllContractAccount(userId, customerKey, auditFlag, haveSettle, selectCom, haveDelivery);
        getDownExcel(jsonObjectList, fieldList, response);
    }

    public void getDownExcel(List<JSONObject> jsonObjectList, String fieldList, HttpServletResponse response) throws Exception {
        //导出表名、列名
        String[] strs = fieldList.split(","); // contractNo;合同号
        int cloumLength = strs.length;
        String columnNameList = "";
        String title = "销售台账信息列表";
        String[] rowsName = new String[cloumLength];
        for (int k = 0; k < strs.length; k++) {
            String zw = strs[k].toString().substring(strs[k].toString().indexOf(";") + 1);
            rowsName[k] = zw;
        }
        int dd = rowsName.length;
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs = null;
        for (int i = 0; i < jsonObjectList.size(); i++) {
            JSONObject jsonObject = jsonObjectList.get(i);
            objs = new Object[rowsName.length];

            for (int j = 0; j < strs.length; j++) {
                String englishFields = strs[j].toString().substring(0, strs[j].toString().indexOf(";"));
                if ("replacementsName".equals(englishFields)) {
                    if (jsonObject.getString(englishFields).equals("wjj")) {
                        objs[j] = "挖掘机";
                    } else if (jsonObject.getString(englishFields).equals("zzj")) {
                        objs[j] = "装载机";
                    } else if (jsonObject.getString(englishFields).equals("qiChe")) {
                        objs[j] = "汽车";
                    } else if (jsonObject.getString(englishFields).equals("fangWu")) {
                        objs[j] = "房产";
                    } else {
                        objs[j] = "其他";
                    }
                } else {
                    objs[j] = jsonObject.getString(englishFields);
                }
            }
            dataList.add(objs);
        }
        ExportCustomerExcel ex = new ExportCustomerExcel(title, rowsName, dataList, response);
        ex.exportContractAccount(cloumLength);
    }


    @RequestMapping(value = "/selectReceivable.json", method = RequestMethod.POST)
    public void selectReceivable(HttpServletResponse response, @RequestBody String jsonData) {
        List<JSONObject> result = this.contractMainFacade.selectReceivable(jsonData);
        if (null != result && result.size() > 0) {
            ResponseUtils.putJsonResponse(response, BaseUtils.succsessArrRespond(result));
        } else {
            ResponseUtils.putJsonResponse(response, BaseUtils.errorrRespond("未找到数据"));
        }
    }

    @RequestMapping(value = "/getSales0List.json", method = RequestMethod.POST)
    public void getSales0List(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = this.contractMainFacade.getSales0List(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(result));
    }

    @RequestMapping(value = "/selectSales0NewList.json", method = RequestMethod.POST)
    public void selectSales0NewList(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = this.contractMainFacade.selectSales0NewList(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(result));
    }

    @RequestMapping(value = "/getRepaymentSender.json", method = RequestMethod.POST)
    public void getRepaymentSender(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = this.contractMainFacade.getRepaymentSender(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(result));
    }

    @RequestMapping(value = "/getContractBuyer.json", method = RequestMethod.POST)
    public void getContractBuyer(HttpServletResponse response, @RequestBody String jsonData) {
        List<JSONObject> result = this.contractMainFacade.getContractBuyer(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessArrRespond(result));
    }

    @RequestMapping(value = "/getRepaymentDate.json", method = RequestMethod.POST)
    public void getRepaymentDate(HttpServletResponse response) {
        List<JSONObject> result = this.contractMainFacade.getRepaymentDate();
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessArrRespond(result));
    }

    @RequestMapping(value = "/senderExpire.json", method = RequestMethod.POST)
    public void senderExpire(HttpServletResponse response) {
        Boolean flag = this.contractMainFacade.senderExpire();
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(String.valueOf(flag)));
    }


    @RequestMapping(value = "/senderMessage.json", method = RequestMethod.POST)
    public void senderMessage(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String mainId = jsonParams.getString("mainId");
        String comName = jsonParams.getString("comName");
        String customerTel = jsonParams.getString("customerTel");
        String content = jsonParams.getString("content");
        contractMainFacade.senderMessage(mainId);
        send(comName, SendConstant.SENDER_PWD, customerTel, content);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond("发送成功"));
    }

    public void send(String comName, String comPwd, String phone, String content) {
        // 存放调用返回的结果,判断成功与否应该分析这个字符串
        String returnCode;
        // 这里修改成你自己的用户名和密码
        Sender sms = new Sender(comName, comPwd);
        // 这里修改成要发送的手机号码和发送内容s
        returnCode = sms.massSend(phone, content, null, null);
        String encode = null;
        try {
            encode = new String(returnCode.getBytes("GBK"), "GB2312");
            System.out.println(encode);
        } catch (Exception e) {
            System.out.println("异常");
        }
    }

    private void sendMessage(String jsonData) {
        List<JSONObject> jsonObjectList = null;
        if (!org.apache.commons.lang3.StringUtils.isBlank(jsonData)) {
            jsonObjectList = FastJsonConvert.convertJSONToArray(jsonData, JSONObject.class);
        }
        if (null != jsonObjectList && jsonObjectList.size() > 0) {
            TextMessage textMessage = new TextMessage(BaseUtils.succsessArrHourTimeRespond(jsonObjectList), true);
            try {
                myWebSocketHandler.sendMsgToAllUsers(textMessage);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping(value = "/selectContractSalesList.json", method = RequestMethod.POST)
    public void selectContractSalesList(HttpServletResponse response, @RequestBody String jsonData) {
        JSONObject result = this.contractMainFacade.selectContractSalesList(jsonData);
        ResponseUtils.putJsonResponse(response, BaseUtils.succsessObjRespond(result));
    }
}